<template>
  <div class="table-wrapper">
    <!-- 筛选区域 -->
    <div ref="filterArea" class="filter-area">
      <div style="display: flex; flex-wrap: wrap; gap: 20px;">
        <!-- 维度选择 -->
        <el-radio-group v-model="selectedDimension" @change="resetDimensionValues">
          <el-radio-button :value="'district'">区/县</el-radio-button>
          <el-radio-button :value="'brand'">品牌</el-radio-button>
          <el-radio-button :value="'store_name'">药店名称</el-radio-button>
        </el-radio-group>

        <el-text class="mx-1" type="info">销售代表:</el-text>
        <el-select
            v-model="selectedSalesReps"
            multiple
            collapse-tags
            placeholder="选择销售代表"
            @change="filterData"
            style="min-width: 50px; width: 200px;"
        >
          <el-option
              v-for="rep in availableSalesReps"
              :key="rep"
              :label="rep"
              :value="rep"
          />
        </el-select>
        <el-text v-if="selectedDimension !== 'store_name'" class="mx-1" type="info">维度值:</el-text>
        <el-select
            v-if="selectedDimension !== 'store_name'"
            v-model="selectedDimensionValues"
            multiple
            collapse-tags
            placeholder="选择维度值"
            style="min-width: 50px; width: 200px;"
            @change="filterData"
        >
          <el-option
              v-for="val in dimensionOptions"
              :key="val"
              :label="val"
              :value="val"
          />
        </el-select>

        <el-text v-if="selectedDimension === 'store_name'" class="mx-1" type="info">门店:</el-text>
        <el-select
            v-if="selectedDimension === 'store_name'"
            v-model="selectedDimensionValues"
            multiple
            collapse-tags
            remote
            reserve-keyword
            filterable
            placeholder="搜索药店名称"
            :remote-method="loadStoreNames"
            :loading="loadingStores"
            @change="filterData"
            style="min-width: 300px; width: 300px;"
        >
          <el-option
              v-for="item in storeNameOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </div>
    </div>
    <div class="table-rotator">
    <!-- 表格 -->
    <div class="table-scroll-container">
      <el-table
          :data="filteredData"
          border
          show-summary
          :summary-method="getSummaries"
          :default-sort="{ prop: 'total', order: 'descending' }"
          style="max-height: 600px; overflow-y: auto;"
      >
        <el-table-column :prop="selectedDimension" :label="leftLabel" fixed="left" width="150" align="center"/>

        <template v-for="salesRep in selectedSalesReps" :key="salesRep">
          <el-table-column :label="salesRep" align="center">
            <template v-for="med in availableMedicines[salesRep]" :key="med">
              <el-table-column
                  :prop="`${salesRep}_${med}`"
                  :label="med"
                  align="center"
                  width="100"
              ></el-table-column>
            </template>
          </el-table-column>
        </template>

        <el-table-column prop="total" label="总计" align="center" fixed="right" width="120"/>
      </el-table>
    </div>
  </div>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, onBeforeUnmount, nextTick, watch} from 'vue'
import type {SaleData} from '../model/sale.ts'

const props = defineProps({
  rawList: {
    type: Array<SaleData>,
    required: true
  }
})

const allData = ref<SaleData[]>([])
const filteredData = ref<any[]>([])

const allSalesReps = ref<string[]>([])
const availableSalesReps = ref<string[]>([])
const selectedSalesReps = ref<string[]>([])

const selectedDimension = ref<'district' | 'store_name' | 'brand'>('district')
const selectedDimensionValues = ref<string[]>([])
const dimensionOptions = ref<string[]>([])

const storeNameOptions = ref<string[]>([])
const loadingStores = ref(false)

const availableMedicines = ref<Record<string, string[]>>({})

const filterArea = ref<HTMLElement | null>(null)
const tableHeight = ref(500)

// 计算表格高度
function calcTableHeight() {
  if (!filterArea.value) return
  const h = window.innerHeight - filterArea.value.offsetHeight - 40
  tableHeight.value = h > 200 ? h : 500
}

import _ from 'lodash';

watch(
    () => props.rawList,
    (newVal, oldVal) => {

      // 统一转换 null 和空白为 '未知'，sale_total 转为数字（parseFloat保证类型）
      allData.value = newVal.map(item => ({
        sales_rep: item.sales_rep || '未知',
        district: item.district || '未知',
        store_name: item.store_name || '未知',
        city: item.city || '未知',
        brand: item.brand || '未知',
        medicine: item.medicine || '未知',
        sale_total: item.sale_total || 0
      }))

      allSalesReps.value = [...new Set(allData.value.map(d => d.sales_rep))]
      selectedSalesReps.value = [...allSalesReps.value]

      updateDimensionOptions()
      filterData()

      // nextTick(() => {
      //   calcTableHeight()
      //   window.addEventListener('resize', calcTableHeight)
      // })

    },
    {immediate: false}
)

onBeforeUnmount(() => {
  window.removeEventListener('resize', calcTableHeight)
})

function updateDimensionOptions() {
  if (selectedDimension.value !== 'store_name') {
    dimensionOptions.value = [...new Set(allData.value.map(d => d[selectedDimension.value]).filter(v => v != null))]
    selectedDimensionValues.value = [...dimensionOptions.value]
  }
}

function resetDimensionValues() {
  selectedDimensionValues.value = []
  if (selectedDimension.value !== 'store_name') {
    updateDimensionOptions()
  }
  filterData()
}

async function loadStoreNames(query: string) {
  if (!query) return
  loadingStores.value = true
  storeNameOptions.value = _(allData.value)
      .map('store_name')                          // 1. 映射：提取所有用户的 'name' 字段
      .filter(name => _.includes(name, query)) // 2. 过滤：保留名字中包含 "球" 的
      .uniq()                               // 3. 去重：移除重复的名字
      .value();
  loadingStores.value = false
}

// 核心过滤与转换成交叉表
function filterData() {
  // 基于维度值过滤
  let filtered = allData.value.filter(item =>
      selectedDimensionValues.value.length === 0 || selectedDimensionValues.value.includes(item[selectedDimension.value])
  )
  // 动态更新销售代表选项
  availableSalesReps.value = [...new Set(filtered.map(d => d.sales_rep))]
  // 销售代表过滤，默认选所有可用
  if (selectedSalesReps.value.length === 0) {
    selectedSalesReps.value = [...availableSalesReps.value]
  } else {
    filtered = filtered.filter(item => selectedSalesReps.value.includes(item.sales_rep))
  }
  // 更新销售代表对应药品
  availableMedicines.value = {}
  selectedSalesReps.value.forEach(rep => {
    availableMedicines.value[rep] = [...new Set(
        filtered.filter(d => d.sales_rep === rep).map(d => d.medicine).filter(m => !!m)
    )]
  })

  // 1. 提前计算出所有需要展示的 (销售代表, 药品) 组合
  // 这一步至关重要，它决定了表格有哪些列
  const allMedicineCombinations: {rep: string, med: string}[] = [];
  selectedSalesReps.value.forEach(rep => {
    const meds = [...new Set(
        filtered.filter(d => d.sales_rep === rep).map(d => d.medicine).filter(m => !!m)
    )];
    availableMedicines.value[rep] = meds; // 顺便更新 availableMedicines
    meds.forEach(med => {
      allMedicineCombinations.push({ rep, med });
    });
  });

  // 2. 生成交叉表结构
  const grouped: Record<string, any> = {};
  filtered.forEach(item => {
    const key = item[selectedDimension.value];
    if (!grouped[key]) {
      // 初始化行对象
      const row: any = { [selectedDimension.value]: key, total: 0 };

      // 为所有可能的组合初始化值为 0
      allMedicineCombinations.forEach(({rep, med}) => {
        row[`${rep}_${med}`] = 0;
      });

      grouped[key] = row;
    }

    const colKey = `${item.sales_rep}_${item.medicine}`;
    let saleTotal = item.sale_total || 0;
    grouped[key][colKey] += saleTotal; // 直接累加，因为已经初始化过了
    grouped[key].total += saleTotal;
  });

  filteredData.value = Object.values(grouped);
}

// 计算总结行数据
function getSummaries({columns, data}: { columns: any[], data: any[] }) {
  const sums: any[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '总计'
      return
    }
    const values = data.map(item => Number(item[column.property] || 0))
    sums[index] = values.reduce((a, b) => a + b, 0)
  })
  return sums
}

const leftLabel = computed(() => {
  if (selectedDimension.value === 'district') return '区/县'
  if (selectedDimension.value === 'brand') return '品牌'
  if (selectedDimension.value === 'store_name') return '药店名称'
  return selectedDimension.value
})
</script>

<style scoped>

/* 内层容器：负责滚动 */
.table-scroll-container {
  width: 100%;
  max-height: 600px; /* 或者你需要的任何最大高度 */
  overflow-x: auto;
  overflow-y: auto;
  box-sizing: border-box;
}

/* 媒体查询：仅作用于外层旋转容器 */
@media (max-width: 767.98px) {
  /* 外层容器：负责旋转和居中 */
  .table-rotator {
    /* 关键：让旋转容器的宽度适应其内容（即内层滚动容器的宽度） */
    display: inline-block;
    transform: rotate(90deg) translateY(-100%);
    transform-origin: top right;

    /* 移除之前复杂的 width, height 和 margin 计算 */
    /* width: 100vh;  <-- 移除 */
    /* height: 100vw; <-- 移除 */
    /* margin: ... <-- 移除 */
  }

  /* 内层容器：在旋转后，宽度和高度需要交换以正确显示 */
  .table-scroll-container {
    width: 100vh; /* 旋转后，视觉上的高度由这个宽度决定 */
    max-height: 100vw; /* 旋转后，视觉上的宽度由这个高度决定 */
  }

  .table-wrapper {
    -ms-overflow-style: none; /* IE/Edge */
    scrollbar-width: none; /* Firefox */
  }

  /* 调整表格单元格对齐（可选，避免文字旋转后错位） */
  .el-table__cell {
    text-align: center;
    vertical-align: middle;
  }
}

.filter-area {
  margin-bottom: 16px;
  flex-shrink: 0;
}

.table-scroll {
  flex: 1;
  overflow: hidden;
}

.el-table th {
  text-align: center;
}
</style>